package com.yzh.wanandroid.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.recyclerview.widget.RecyclerView
import com.yzh.wanandroid.R
import com.yzh.wanandroid.databinding.ItemLoadstateBinding

/**
 *  Paging3 自带的footer view,用来显示上拉加载提示
 */
class LoadStateFooterAdapter(private val retry: () -> Unit) :
    LoadStateAdapter<LoadStateFooterAdapter.LoadStateViewHolder>() {

    private val TAG = "LoadStateFooterAdapter"

    override fun onBindViewHolder(holder: LoadStateViewHolder, loadState: LoadState) {
        holder.bindState(loadState)
    }

    override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): LoadStateViewHolder {
        return LoadStateViewHolder(parent, retry)
    }

    inner class LoadStateViewHolder(parent: ViewGroup, var retry: () -> Unit) : RecyclerView.ViewHolder(
        LayoutInflater.from(parent.context)
            .inflate(R.layout.item_loadstate, parent, false)
    ) {
        var itemLoadStateBindingUtil: ItemLoadstateBinding = ItemLoadstateBinding.bind(itemView)
        fun bindState(loadState: LoadState) {
            when (loadState) {
                is LoadState.Error -> {
                    itemLoadStateBindingUtil.footerLoadingProgress.visibility = View.GONE
                    itemLoadStateBindingUtil.footerLoadingMessage.text =
                        itemView.context.getString(R.string.load_error)
                    itemLoadStateBindingUtil.footerLoadingLayout.setOnClickListener {
                        retry()
                    }
                }
                is LoadState.Loading -> {
                    itemLoadStateBindingUtil.footerLoadingProgress.visibility = View.VISIBLE
                    itemLoadStateBindingUtil.footerLoadingMessage.text =
                        itemView.context.getString(R.string.loading)
                }
            }
        }
    }
}